#include <stdio.h>
#include <stdlib.h>
#include "libimg.h"
#include "tp3.h"
#include <math.h>

  int calculahash(char *chave,int tamreg){
    int hash=0, i=0, a=1;
    for(i=0;i<tamreg-1;i++){
      if(chave[a]>chave[i]){
        hash=hash+5;
      }
      if(chave[a]==chave[i]){
        hash=hash+3;
      }
      if(chave[a]<chave[i]){
        hash=hash+2;
      }
      a++;
    }
    hash=hash%11;
    return(hash);
  }

  void criahashPK(FILE *base){
    int i=0,hn=0,nPK=0,a;
    PK *lista;
    FILE *arq;
    char buffer[200], fname[8];
    lista=(PK*)malloc(sizeof(PK)*20);
    while(hn<12){
      while(fgets(buffer,200,base)!=NULL){
        fseek(base,450*i,0);
        fread(buffer,1,200,base);
        if(calculahash(buffer,200)==hn){
          nPK++;
          AdicionaPK(lista,buffer,nPK,i);
        }
        i++;
        fseek(base,450*i,0);
      }
      if(hn<10){
        sprintf(fname,"P0%d.dat",hn);
      }
      else{
        sprintf(fname,"P%d.dat",hn);    
      }
      arq=fopen(fname,"w+");
      gravaPK(lista,nPK,arq);
      fclose(arq);
      free(lista);
      lista=(PK*)malloc(sizeof(PK)*20);
      hn++;
      nPK=0;
      i=0;
      fseek(base,0,0);
    }
    free(lista);
  }
  
  void criaDescritores(){
    int i=0,hn=0,nPK=0,a;
    PK *lista;
    FILE *arq;
    char buffer[200], fname[8];
    lista=(PK*)malloc(sizeof(PK)*20);
    i=0;
    while(hn<12){
      while(fgets(buffer,200,base)!=NULL){
        fseek(base,450*i,0);
        fread(buffer,1,200,base);
        if(CalcDDescritor(CalculaDescritor(buffer))==hn){
          nPK++;
          AdicionaPK(lista,buffer,nPK,i);
        }
        i++;
        fseek(base,450*i,0);
      }
      if(hn<10){
        sprintf(fname,"V0%d.dat",hn);
      }
      else{
        sprintf(fname,"V%d.dat",hn);    
      }
      arq=fopen(fname,"w+");
      gravaPK(lista,nPK,arq);
      fclose(arq);
      free(lista);
      lista=(PK*)malloc(sizeof(PK)*20);
      hn++;
      nPK=0;
      i=0;
      fseek(base,0,0);
    }
    free(lista);
  }
  
  int CalcFDescritor(char x){
    int a=7,i=0;
    while(x!=0){
      if(x>pow(2,a)){
        x=x-pow(2,a);
        a--;
        i++;
      }
      else{
        a--;     
      }
    }
    return i;
  }
  
  void AdicionaDS(DS *lista, 
